#coding:utf-8

from django.http import HttpResponse,HttpResponseRedirect
from django.core.paginator import PageNotAnInteger, Paginator, InvalidPage, EmptyPage
from groups.models import Group
from login.models import Register
from django import template
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse
from django.shortcuts import render
from PIL import Image
from django.contrib import messages
#from django.views.decorators.csrf import csrf_protect
from users.models import Info,Teacher,News,Review_of_news,Message,Follow_topic,Follow_user,Follow_group,Follow_course,Post_reward,Post_course,Purchase,Good_news,Good_review_of_news,Warning_mes,Feedback
from groups.models import Group,Topic,Review_of_topic,Good_review_of_topic,Group_file
from rewards.models import Reward,Uncover,Reward_mes,Reward_course,Reward_lession
from courses.models import Types,Tiny_type,Course,Lession,Course_comment
from django.utils import timezone
from django.db.models import Q
import sys
from remind import warn
reload(sys)
sys.setdefaultencoding('utf-8')
import re,md5,os,time,json,base64,qiniu.io,qiniu.conf,qiniu.rs,math


class PutPolicy(object):
    scope = 'maizhi'
    expires = 3600
    callbackUrl = None
    callbackBody = None
    returnUrl = None
    returnBody = None
    endUser = None
    asyncOps = None

    def __init__(self, scope):
        self.scope = scope

    qiniu.conf.ACCESS_KEY = "EW8idy4EFnJDBicDJZhPIVIVDU9AL0g4waW5MNtJ"
    qiniu.conf.SECRET_KEY = "C1qaP_-sgjVgQb6GGHJ-vCle0qTiGI8qtbgOumOB"

#首页显示
def index(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    #sta=0
    #if 'sta' in request.GET:
    #	sta=1
    #分页，每页显示10条
    limit = 10
    focus=Follow_user.objects.filter(user_id=request.session['id'])
    fs=[]
    for f in focus:
        fs.append(f.follow_user_id)
    topics = News.objects.filter(user_id__in=fs).order_by('-id')
    paginator = Paginator(topics, limit)
    page = request.GET.get('page')
    try:
        topics = paginator.page(page)
    except PageNotAnInteger:
        topics = paginator.page(1)
    except EmptyPage:
        topics = paginator.page(paginator.num_pages)
    #将新鲜事信息存储在result列表中
    result=[]
    for t in topics:
        each=[]
        i=Info.objects.get(user_id=t.user_id)
        each.append(i.user_name)  #0
        each.append(i.img)        #1
        each.append(t.content)    #2
        each.append(t.time)       #3
        if t.src:
            each.append(t.src)    #4
        else:
            each.append('')       #4
        each.append(t.good_con)   #5
        each.append(t.share_con)  #6
        each.append(t.review_con) #7
        each.append(t.id)         #8
        each.append(i.sign)       #9
        each.append(t.user_id)    #10
        each.append(i.position)   #11
        each.append(i.work)       #12
        #新鲜事的回复,刚开始只显示一条
        re_of_news=Review_of_news.objects.filter(news_id=t.id).order_by('-time')[0:1]
        for r in re_of_news:
            each.append(r.id)			#13
            each.append(r.content)		#14
            info=Info.objects.get(user_id=r.from_id)
            each.append(info.user_name)	#15
            each.append(info.img)		#16
            each.append(r.to)			#17
            each.append(r.good_con)	 	#18
            each.append(r.time)		 	#19
            each.append(r.review_con)	#20
            each.append(r.from_id)		#21
            each.append(info.domain)	#22
        result.append(each)
    info=Info.objects.get(user_id=request.session['id'])

    #havent=0
    #for n in m:
        #if n.status==1:
        #havent+=1
    #mesCon=Message.objects.filter(to=request.session['id']).filter(status=1).count()
    #havent+=int(mesCon)
    #用户的权限purview=1:普通发布者,purview=2:企业用户
    purview=''
    if int(request.session['status'])==int(2):
        purview='1'
    elif int(request.session['status'])==int(3):
        purview='2'
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    #my_group_set=Group.objects.filter(user_id=request.session['id'])
    #my_group_id=[]
    #for m in my_group_set:
    #	my_group_id.append(m.id)
    #话题动态处
    follow_group_set=Follow_group.objects.filter(user_id=request.session['id'])
    follow_groups=[]
    for f in follow_group_set:
        #if f.follow_group_id in my_group_id:
        #	pass
        #else:
            follow_groups.append(int(f.follow_group_id))

    groupAndTwoTopic=[]
    #随机获取一个小组
    group_set=Group.objects.exclude(user_id=request.session['id']).order_by('?')[0:1]
    for g in group_set:
        groupAndTwoTopic.append(g.id)		#0
        groupAndTwoTopic.append(g.name)		#1
        groupAndTwoTopic.append(g.domain)		#2
        groupAndTwoTopic.append(g.img)		#3

        if int(g.id) in follow_groups:
            groupAndTwoTopic.append(1)		#4
        else:
            groupAndTwoTopic.append(2)		#4

        twoTopic_set=Topic.objects.filter(group_id=g.id).order_by('-time')[0:2]
        for t in twoTopic_set:
            groupAndTwoTopic.append(t.id)		#5  #7
            groupAndTwoTopic.append(t.name)		#6  #8



    #热门课程处
    hot_course_set=Course.objects.filter().order_by("-purchase_con")[0:2]
    #活跃用户处
    hot_user_set=Info.objects.exclude(user_id=request.session['id']).order_by('?')[0:2]
    my_follow_set=Follow_user.objects.filter(user_id=request.session['id'])
    follow_users=[]
    for m in my_follow_set:
        follow_users.append(int(m.follow_user_id))
    hot_user=[]
    for h in hot_user_set:
        each=[]
        each.append(h.user_id)		#0
        each.append(h.user_name)		#1
        each.append(h.domain)		#2
        each.append(h.img)		#3
        if int(h.user_id) in follow_users:
            each.append(1)		#4  if follow
        else:
            each.append(2)		#4  if not follow
        each.append(h.work)		#5
        hot_user.append(each)





    return render(request,'users/index.html',{"s":follow_groups,'hotuser':hot_user,'hotcourse':hot_course_set,'groupAndTwoTopic':groupAndTwoTopic,'purview':purview,'id':request.session['id'],'info':info,'result':result,'topics':topics,'message':mess,'havent':havent,'waningMes':waningMes})

def header_warning(request):
    warning_id=request.GET['warning_id']
    warning=Warning_mes.objects.get(id=warning_id)
    warning.if_read=1
    warning.save()
    return HttpResponse(1)

def warning_news_page(request):
    warning_id=request.GET['warning_id']
    warning=Warning_mes.objects.get(id=warning_id)
    warning.if_read=1
    warning.save()
    news_id=request.GET['news_id']
    #allNews_con=News.objects.all().count()
    #afterNews_con=News.objects.filter(id__gt=news_id).count()
    #page=int(math.ceil((float(allNews_con)-float(afterNews_con))/10))
    focus=Follow_user.objects.filter(user_id=request.session['id'])
    fs=[]
    for f in focus:
        fs.append(f.follow_user_id)
    beforeNews_con=News.objects.filter(id__gt=news_id).filter(user_id__in=fs).count()
    page=int(math.ceil((float(beforeNews_con)+1.00)/10.00))
    return HttpResponse(page)

#发布新鲜事
@csrf_exempt
def publish(request):
    #try:
        policy = qiniu.rs.PutPolicy('mzimage')
        uptoken = policy.token()
        tj=time.time()
        #新鲜事中的图片处理
        if 'img' in request.POST:
            #u=request.POST['img'].split(',')
            #i=base64.decodestring(u[1])
            #suffix=request.POST['img'].name.split('.')[-1]
            dirs="templates/picture/news/"+str(tj)
            files=open("templates/picture/news/"+str(tj), "w")
            files.write(request.POST['img'].replace('*','+'))
            files.close()
            news=request.POST['news']
            domain='http://mzimage.qiniudn.com'
            News(user_id=request.session['id'],src=domain+'/'+str(tj),content=news,good_con=0,share_con=0,review_con=0,img=str(tj)).save()
            jpg("templates/picture/news/"+str(tj),"templates/picture/news/"+str(tj))
            ret=qiniu.io.put_file(uptoken,str(tj),r"e:/Demo/templates/picture/news/"+str(tj))
            if ret:
                os.remove(dirs)
            return HttpResponse('1')
        else:
            news=request.POST['news']
            News(user_id=request.session['id'],content=news,good_con=0,share_con=0,review_con=0,img="").save()
            return HttpResponse('1')
    #except:
    #	return HttpResponse('0')

#修改图片编码
def jpg(url,jpg):
    files=open(url)
    fr=files.read()
    frd=fr.split(',')
    decode=base64.decodestring(frd[1])
    files.close()
    f=open(jpg,'w')
    f.write(decode)
    f.close()

#新鲜事的赞
def good(request):
    entire=Good_news.objects.filter(news_id=request.GET['newsid'])
    for i in entire:
        if request.session['id']==i.user_id:
            return HttpResponse('2')
    Good_news(news_id=request.GET['newsid'],user_id=request.session['id']).save()
    n=News.objects.get(id=request.GET['newsid'])
    g=int(n.good_con)+int(1)
    n.good_con=g
    to=n.user_id
    n.save()
    #添加一条提醒
    try:
        if_exit_good_table=Warning_mes.objects.filter(aim_id=int(request.GET['newsid'])).get(status=9)
    except:
        if_exit_good_table=0

    if if_exit_good_table==0:
        warning_mesTable=Warning_mes(from_id=int(request.session['id']),to=int(to),aim_id=int(request.GET['newsid']),status=9)
        warning_mesTable.save()

    return HttpResponse('1')

#发布私信
def message(request):
    realto=News.objects.get(id=request.GET['to'])
    Message(from_id=request.session['id'],to=realto.user_id,content=request.GET['message'],status=1).save()
    return HttpResponse('1')

#分享
def share(request):
    try:
        sharemsg=str(request.GET['sharemsg'])+str(request.GET['before'])
        News(user_id=request.session['id'],content=sharemsg,good_con=0,share_con=0,review_con=0,img="",src=request.GET['img']).save()
        oldnews=News.objects.get(id=request.GET['id'])
        oldnews.share_con+=1
        oldnews.save()
        return HttpResponse('OK')
    except:
        return HttpResponse('Wrong')

#修改头像
def head(request):
    info=Info.objects.get(user_id=request.session['id'])
    policy = qiniu.rs.PutPolicy('mzhead')
    uptoken = policy.token()
    if 'picture' in request.FILES:
        tj=time.time()
        image=request.FILES['picture']
        #获取图片的拓展名
        suffix=image.name.split('.')[-1]
        #Python的Image库
        image=Image.open(image)
        (x,y)=image.size
        x_s=330
        y_s=y*x_s/x
        little_img = image.resize((x_s,y_s),Image.ANTIALIAS)
        coordinate=request.POST['coordinate'].split('*')
        region = (int(round(float(coordinate[0]))+1),int(coordinate[1]),int(coordinate[2]),int(coordinate[3]))
        #region=(0,0,100,100)
        cropImg = little_img.crop(region)
        #cropImg=pic.thumbnail((int(coordinate[2]),int(coordinate[3])),Image.ANTIALIAS)
        cropImg.save(r"e:/Demo/templates/picture/avatar/"+str(tj)+'.'+suffix)
        domain="http://mzhead.qiniudn.com"
        #dirs ='templates/picture/avatar/'+str(tj)
        #if os.path.isfile(dirs):
        #	os.remove(dirs)
        #fp=open(dirs, 'wb')
        #content=pic.read()
        #fp.write(content)
        #fp.flush()
        #fp.close()
        ret=qiniu.io.put_file(uptoken,str(tj),r"e:/Demo/templates/picture/avatar/"+str(tj)+'.'+suffix)
        #if ret:
        #	os.remove(dirs)
        info.img=str(tj)
        info.domain=domain
        info.time=timezone.now()
        info.save()
    #return HttpResponse(image)
    messages.add_message(request, messages.SUCCESS, '修改成功！')
    return HttpResponseRedirect(reverse('users:setting'))
    #return render(request,"login/home.html")


    #def getimg(request):
    #	this=News.objects.get(id=request.GET['imgid'])
    #	if this.img:
    #		return HttpResponse(this.img)
    #	else:
    #		return HttpResponse('')

    #def mycourseact(request):
    #	return render(request,'users/myCourseAct.html')

#个人主页,u_id为用户的id
def home(request,u_id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    #获取home页面的tab标签的具体的某一签
    if 'tab' in request.GET:
        tab=int(request.GET['tab'])
    else:
        tab=1
    info=Info.objects.get(user_id=request.session['id'])
    #判断页面是否是自己的主页,1:我的主页,2:他人主页
    if int(u_id)==int(request.session['id']):
        identity='1'
        userinfo=Info.objects.get(user_id=request.session['id'])
        newsTable=News.objects.filter(user_id=request.session['id']).order_by('-time')
    else:
        identity='0'
        userinfo=Info.objects.get(user_id=u_id)
        newsTable=News.objects.filter(user_id=u_id).order_by('-time')
    #用户推荐，除去已关注的
    user=Info.objects.all().order_by('?')[0:5]
    guy=[]
    focus=[]
    f=Follow_user.objects.filter(user_id=request.session['id'])
    for j in f:
        focus.append(int(j.follow_user_id))
    if int(u_id) in focus :
        btn=1
    else :
        btn=0

    for u in user:
        if u.id==request.session['id'] :
            pass
        elif u.user_id in focus :
            pass
        else:
            each=[]
            i=Info.objects.get(user_id=u.user_id)
            each.append(i.user_name)		#0
            each.append(i.sign)				#1
            each.append(i.sex)				#2
            each.append(i.img)				#3
            each.append(i.user_id)				#4
            each.append(i.domain)			#5
            guy.append(each)
    #新鲜事，存储在news列表中
    news=[]
    for t in newsTable:
        each=[]
        i=Info.objects.get(user_id=t.user_id)
        each.append(i.user_name)  #0
        each.append(t.img)        #1
        each.append(t.content)    #2
        each.append(t.time)       #3
        if t.src:
            each.append(t.src)    #4
        else:
            each.append('')       #4
        each.append(t.good_con)   #5
        each.append(t.share_con)  #6
        each.append(t.review_con) #7
        each.append(t.id)         #8
        each.append(i.sign)       #9
        each.append(t.user_id)    #10
        each.append(i.position)   #11
        each.append(i.work)       #12
        #新鲜事的回复
        re_of_news=Review_of_news.objects.filter(news_id=t.id).order_by('-time')[0:1]
        for r in re_of_news:
            each.append(r.id)			#13
            each.append(r.content)		#14
            info=Info.objects.get(user_id=r.from_id)
            each.append(info.user_name)	#15
            each.append(info.img)		#16
            each.append(r.to)			#17
            each.append(r.good_con)	 	#18
            each.append(r.time)		 	#19
            each.append(r.review_con)	#20
            each.append(r.from_id)		#21
            each.append(info.domain)			#22
        news.append(each)
    #我创建的小组
    my=Group.objects.filter(user_id=u_id)
    #我加入的小组
    fg=Follow_group.objects.filter(user_id=u_id)
    follow=[]
    for l in fg:
        follow.append(l.follow_group_id)
    mygroup=[]
    for k in my:
        each=[]
        each.append(k.name)			#0
        each.append(k.domain)		#1
        each.append(k.img)			#2
        each.append(k.introduce)	#3
        if k.id in follow:
            each.append('1')		#4
        else:
            each.append('0')		#4
        each.append(k.id)			#5
        #获取两条
        topicTable=Topic.objects.filter(group_id=k.id).order_by('-time')[0:3]
        topics=[]
        for t in topicTable:
            eachTopic=[]
            eachTopic.append(t.id)	##0
            eachTopic.append(t.name)	##1
            t_content=t.content
            t_content=re.sub(r'<img.*>','',str(t_content))
            eachTopic.append(t_content)	##2
            eachTopic.append(t.time)	##3
            topics.append(eachTopic)
        each.append(topics)				#6

        #Topic.objects.filter(group_id=k.id).order_by('-review_con')[0:3]
        mygroup.append(each)
    Follow_group_set1=Group.objects.filter(id__in=follow).order_by('-time')[0:6]
    Follow_group_set2=Group.objects.filter(id__in=follow).order_by('-time')[6:]
    follow_group_set1=[]
    for f in Follow_group_set1:
        each=[]
        each.append(f.id)
        each.append(f.domain)
        each.append(f.img)
        each.append(f.name)
        follow_group_set1.append(each)
    follow_group_set2=[]
    for f in Follow_group_set2:
        each=[]
        each.append(f.id)
        each.append(f.domain)
        each.append(f.img)
        each.append(f.name)
        follow_group_set2.append(each)

    courseTable=Course.objects.filter(teacher_id=u_id).order_by('-time')
    couses=[]
    for c in courseTable:
        each=[]
        each.append(c.id)		#0
        each.append(c.name)		#1
        each.append(c.domain)	#2
        each.append(c.img)		#3
        each.append(c.introduce)	#4
        each.append(c.price)	#5
        each.append(c.grade_con)	#6


        col=0
        if int(u_id)==request.session['id']:
            col=1
        else:
            follow_courseTable=Follow_course.objects.filter(user_id=request.session['id'])
            for f in follow_courseTable:
                if int(f.follow_course_id)==int(c.id):
                    col=1
                    break
        each.append(col)		#7 if collect
        yellow_stars=range(0,c.grade)
        each.append(yellow_stars)		#8
        hollow_stars=range(0,(5-c.grade))
        each.append(hollow_stars)		#9
        pur=0
        if int(u_id)==request.session['id']:
            pur=1
        else:
            purchaseTable=Purchase.objects.filter(user_id=request.session['id'])
            for p in purchaseTable:
                if int(p.purchase_id)==int(c.id):
                    pur=1
                    break
        each.append(pur)		#10 if purchase
        couses.append(each)

    rewardTable=Reward.objects.filter(from_id=u_id).order_by('-time')
    reward=[]
    for r in rewardTable:
        each=[]
        each.append(r.id)		#0
        each.append(r.name)		#1
        each.append(r.price)	#2
        each.append(r.introduce)	#3
        r_type=Types.objects.get(id=r.types_id)
        each.append(r_type.name)	#4
        visited_info=Info.objects.get(user_id=u_id)
        each.append(visited_info.domain)  #5
        each.append(visited_info.img)		#6
        reward.append(each)


    paginator = Paginator(news, 10)
    page = request.GET.get('page1')
    try:
        news = paginator.page(page)
    except PageNotAnInteger:
        news = paginator.page(1)
    except EmptyPage:
        news = paginator.page(paginator.num_pages)

    paginator = Paginator(mygroup, 10)
    page = request.GET.get('page2')
    try:
        mygroup = paginator.page(page)
    except PageNotAnInteger:
        mygroup = paginator.page(1)
    except EmptyPage:
        mygroup = paginator.page(paginator.num_pages)

    paginator = Paginator(couses, 10)
    page = request.GET.get('page3')
    try:
        couses = paginator.page(page)
    except PageNotAnInteger:
        couses = paginator.page(1)
    except EmptyPage:
        couses = paginator.page(paginator.num_pages)

    paginator = Paginator(reward, 30)
    page = request.GET.get('page4')
    try:
        reward = paginator.page(page)
    except PageNotAnInteger:
        reward = paginator.page(1)
    except EmptyPage:
        reward = paginator.page(paginator.num_pages)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    statu=request.session['status']
    purview=''
    if int(statu)==int(2):
        purview='1'
    elif int(statu)==int(3):
        purview='2'
    return render(request,'users/home.html',{'focus':focus,'waningMes':waningMes,"purview":purview,'btn':btn,'havent':havent,'reward':reward,'follow_group_set1':follow_group_set1,'follow_group_set2':follow_group_set2,'tab':tab,'couses':couses,'mygroup':mygroup,'identity':identity,'userinfo':userinfo,'info':info,'guy':guy,'news':news,'message':mess,'u_id':u_id})

def add(request):
    f=Follow_user.objects.filter(user_id=request.session['id'])
    follow=[]
    for i in f:
        follow.append(i.follow_user_id)
    if int(request.GET['id']) in follow:
        Follow_user.objects.filter(user_id=request.session['id']).get(follow_user_id=request.GET['id']).delete()
        focus=Info.objects.get(user_id=request.session['id'])
        focus.focus_con-=1
        focus.save()
        fan=Info.objects.get(user_id=request.GET['id'])
        fan.fan_con-=1
        fan.save()
    else:
        Follow_user(user_id=request.session['id'],follow_user_id=request.GET['id']).save()
        focus=Info.objects.get(user_id=request.session['id'])
        focus.focus_con+=1
        focus.save()
        fan=Info.objects.get(user_id=request.GET['id'])
        fan.fan_con+=1
        fan.save()
    return HttpResponse('1')

def managecourse(request):
    #if not 'id' in request.session:
    #	return HttpResponseRedirect(reverse('login:index'))
    auth = 0
    error = 0
    if int(request.session['status']) == 2:
        auth = 1
    #无记录检查

    info=Info.objects.get(user_id=request.session['id'])
    purchase=Purchase.objects.filter(user_id=request.session['id'])

    if purchase.count() == 0:
        error = 1
        jump_url = reverse('courses:coursecreate')
        return render(request, 'users/manageCourse.html', {'info':info, 'error':error, 'jump_url': jump_url})

    pur_course=[]
    for i in purchase:
        each=[]
        c=Course.objects.get(id=i.purchase_id)
        each.append(c.name)				#0
        each.append(c.domain)			#1
        each.append(c.img)				#2
        each.append(c.id)				#3
        each.append(i.time)				#4
        f=Info.objects.get(user_id=i.teacher_id)
        each.append(f.user_name)		#5
        each.append(f.user_id)			#6
        each.append(c.price)			#7
        each.append(i.comment)			#8
        pur_course.append(each)
    reward=Reward_course.objects.filter(to_id=request.session['id'])
    rew_course=[]
    for j in reward:
        each=[]
        each.append(j.name)				#0
        each.append(j.domain)			#1
        each.append(j.img)				#2
        each.append(j.id)				#3
        each.append(j.time)				#4
        f=Info.objects.get(id=j.teacher_id)
        each.append(f.user_name)		#5
        each.append(f.user_id)			#6
        each.append(j.password)			#7
        each.append(j.reward_id)		#8
        rew_course.append(each)
    follow=Follow_course.objects.filter(user_id=request.session['id'])
    fol_course=[]
    for k in follow:
        each=[]
        c=Course.objects.get(id=int(k.follow_course_id))
        each.append(c.name)				#0
        each.append(c.domain)			#1
        each.append(c.img)				#2
        each.append(c.id)				#3
        f=Info.objects.get(id=c.teacher_id)
        each.append(f.user_name)		#4
        each.append(f.user_id)			#5
        each.append(c.price)			#6
        p=Purchase.objects.filter(purchase_id=c.id)
        if p :
            each.append(1)				#7
        else :
            each.append(0)				#7
        fol_course.append(each)
    course=Course.objects.filter(teacher_id=request.session['id'])
    crs=[]
    for n in course:
        deadtime=str(n.deadline).split('.')
        deadline=deadtime[0]
        timeArray=time.strptime(deadline,"%Y-%m-%d %H:%M:%S")
        timeStamp=int(time.mktime(timeArray))
        #x = time.localtime(timeStamp+2592000)
        #reward.deadline=time.strftime('%Y-%m-%d %H:%M:%S',x)
        each=[]
        if int(timeStamp) > int(time.time()):
            each.append(0)			#0
        else:
            each.append(1)			#0
        each.append(n.id)			#1
        each.append(n.name)			#2
        each.append(n.domain)		#3
        each.append(n.img)			#4
        each.append(n.price)		#5
        each.append(n.purchase_con)	#6
        each.append(n.deadline)		#7
        crs.append(each)
    publish=Reward_course.objects.filter(teacher_id=request.session['id']).filter(over=1)
    pbs=[]
    for l in publish:
        deadtime=str(l.deadline).split('.')
        deadline=deadtime[0]
        timeArray=time.strptime(deadline,"%Y-%m-%d %H:%M:%S")
        timeStamp=int(time.mktime(timeArray))
        #x = time.localtime(timeStamp+2592000)
        #reward.deadline=time.strftime('%Y-%m-%d %H:%M:%S',x)
        each=[]
        if timeStamp > int(time.time()):
            each.append(0)			#0
        else:
            each.append(1)			#0
        each.append(l.id)			#1
        each.append(l.name)			#2
        each.append(l.domain)		#3
        each.append(l.img)			#4
        each.append(l.price)		#5
        each.append(l.time)			#6
        pbs.append(each)
    #发布的悬赏的课程
    publishing=Reward_course.objects.filter(teacher_id=request.session['id']).filter(over=0)
    ing=[]
    for f in publishing:
        r=Reward.objects.get(id=f.reward_id)
        each=[]
        if int(r.from_id)==int(request.session['id']):
            each.append(1)			#0
        else:
            each.append(0)			#0
        if int(r.to)==int(request.session['id']):
            each.append(1)			#1
        else:
            each.append(0)			#1
        each.append(f.domain)		#2
        each.append(f.img)			#3
        each.append(f.name)			#4
        each.append(f.price)		#5
        i=Info.objects.get(user_id=f.to_id)
        each.append(i.user_name)	#6
        each.append(f.id)			#7
        each.append(f.password)		#8
        each.append(r.time)			#9
        ing.append(each)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request, 'users/manageCourse.html',{'info':info, 'auth':auth, 'waningMes':waningMes,
                                                     'havent':havent, 'message':mess, 'purchase':pur_course,
                                                     'reward':rew_course, 'follow':fol_course, 'course':crs,
                                                     'publish':pbs, 'ing':ing})

#管理我的小组，包括加入的和我创建的
def managegroup(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    info=Info.objects.get(user_id=request.session['id'])
    followGroup=Follow_group.objects.filter(user_id=request.session['id'])
    groups=Group.objects.filter(user_id=request.session['id'])
    myGroupId=[]
    for i in groups:
        myGroupId.append(i.id)
    follow=[]
    for o in followGroup:
        if o.follow_group_id in myGroupId:
            pass
        else:
            follow.append(o.follow_group_id)
    limit=15
    paginator = Paginator(follow, limit)
    page = request.GET.get('page')
    try:
        follow = paginator.page(page)
    except PageNotAnInteger:
        follow = paginator.page(1)
    except EmptyPage:
        follow = paginator.page(paginator.num_pages)
    #我加入的小组，信息存储在groups列表中
    groups=[]
    for i in follow:
        each=[]
        group=Group.objects.get(id=i)
        if group.status==2:
            k=Info.objects.get(user_id=group.user_id)
            each.append(group.id)          #0
            each.append(group.name)        #1
            each.append(group.crew_con)    #2
            each.append(k.user_name)    #3
            each.append(k.user_id)      #4
            each.append(group.img)         #5
            each.append(group.domain)      #6
            groups.append(each)
    my=Group.objects.filter(user_id=request.session['id']).filter(status=2)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/manageGroup.html',{'groups':groups,'waningMes':waningMes,'follow':follow,'my':my,'message':mess,'havent':havent,'info':info})

#我的悬赏，包括我发布的悬赏和我揭的悬赏
def managereward(request):
    info=Info.objects.get(user_id=request.session['id'])
    rewards=Reward.objects.filter(from_id=request.session['id']).order_by('deadline')
    #我发布的悬赏，信息存储在groups列表中
    reward=[]
    for i in rewards:
        each=[]
        each.append(i.name)				#0
        each.append(i.message_con)		#1
        each.append(i.uncover_con)		#2
        each.append(i.deadline)			#3
        each.append(i.id)				#4
        each.append(i.status)			#5
        u=Uncover.objects.filter(reward_id=i.id)
        #获取揭单的人的信息
        all_uncover_person=[]
        for k in u:
            each1=[]
            each1.append(k.id)
            l=Info.objects.get(user_id=k.to)
            each1.append(l.user_name)
            each1.append(k.to)
            all_uncover_person.append(each1)
        each.append(all_uncover_person)	#6
        reward.append(each)
    #我揭的悬赏
    my=Uncover.objects.filter(to=request.session['id'])
    uncover=[]
    for j in my:
        each=[]
        r=Reward.objects.get(id=j.reward_id)
        each.append(r.name)				#0
        each.append(r.message_con)		#1
        each.append(r.uncover_con)		#2
        each.append(r.id)				#3
        each.append(j.status)			#4
        i=Info.objects.get(user_id=r.from_id)
        each.append(i.user_name)		#5
        uncover.append(each)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/manageReward.html',{'info':info,'reward':reward,'uncover':uncover,'waningMes':waningMes,'havent':havent,'message':mess})

#管理我的好友
def managefriend(request):
    info=Info.objects.get(user_id=request.session['id'])
    #我关注的
    myfollow_set=Follow_user.objects.filter(user_id=request.session['id']).exclude(follow_user_id=request.session['id'])
    myfollow_ids=[]
    for m in myfollow_set:
        myfollow_ids.append(m.follow_user_id)
    myfollow=Info.objects.filter(user_id__in=myfollow_ids)
    #关注我的
    followme_set=Follow_user.objects.filter(follow_user_id=request.session['id']).exclude(user_id=request.session['id'])
    followme_ids=[]
    for f in followme_set:
        followme_ids.append(f.user_id)
    follow_me_all=Info.objects.filter(user_id__in=followme_ids)
    follow_me=[]
    for f in follow_me_all:
        each=[]
        each.append(f.user_id)		#0
        each.append(f.domain)		#1
        each.append(f.img)		#2
        each.append(f.user_name)		#3
        each.append(f.work)		#4
        each.append(f.sex)		#5
        each.append(f.position)		#6
        try:
            Follow_user.objects.filter(user_id=request.session['id']).get(follow_user_id=f.user_id)
            each.append(1)		#7 if I follow him
        except:
            each.append(2)		#7 if I do not follow him
        follow_me.append(each)

    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/managefriend.html',{'follow_me':follow_me,'myfollow':myfollow,'info':info,'waningMes':waningMes,'havent':havent,'message':mess})

#取消关注
def cancelfocus(request):
    focus_id=request.GET['u_id']
    the_follow=Follow_user.objects.filter(user_id=request.session['id']).get(follow_user_id=focus_id)
    the_follow.delete()
    myInfo=Info.objects.get(user_id=request.session['id'])
    myInfo.fan_con=int(myInfo.fan_con)-1
    myInfo.save()
    yourInfo=Info.objects.get(user_id=focus_id)
    yourInfo.focus_con=int(yourInfo.focus_con)-1
    yourInfo.save()
    return HttpResponse('1')

#添加关注
def addfocus(request):
    focus_id=request.GET['u_id']
    add_the_focus=Follow_user(user_id=request.session['id'],follow_user_id=focus_id)
    add_the_focus.save()
    myInfo=Info.objects.get(user_id=request.session['id'])
    myInfo.focus_con=int(myInfo.focus_con)+1
    myInfo.save()
    yourInfo=Info.objects.get(user_id=focus_id)
    yourInfo.fan_con=int(yourInfo.fan_con)-1
    yourInfo.save()
    return HttpResponse('1')

#个人设置页面
def setting(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    info=Info.objects.get(user_id=request.session['id'])
    user=Register.objects.get(id=request.session['id'])
    status=None
    if user.status!="0":
        status=True
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/setting.html',{'email':request.session['email'],'info':info,'waningMes':waningMes,'havent':havent,'message':mess})

#个人设置后台
def update(request):
    #try:
    info=Info.objects.get(user_id=request.session['id'])
    info.user_name=request.POST['name']
    info.sex=request.POST['sex']
    info.work=request.POST['work']
    info.position=request.POST['position']
    info.birthday=request.POST['birthday']
    info.constellation=request.POST['constellation']
    info.sign=request.POST['sign']
    info.introduce=request.POST['introduce']
    info.save()
    messages.add_message(request, messages.SUCCESS, '修改成功！')
    return HttpResponseRedirect(reverse('users:setting'))
    #except:
    #	return HttpResponse('Login first')

#修改密码
def pwdchange(request):
    user=Register.objects.get(id=request.session['id'])
    old_pwd=request.POST['old_pwd']
    pwd=user.password
    if md5.new(old_pwd).hexdigest()==pwd:
        new_pwd=request.POST['new_pwd']
        if old_pwd!=new_pwd:
            user.password=md5.new(new_pwd).hexdigest()
            user.save()
            return HttpResponseRedirect(reverse('login:index'))
    else:
        return HttpResponse('原密码不正确！')

#新鲜事的回复
def comment(request):
    news_id=request.GET['news_id']
    content=request.GET['content']
    from_id=request.session['id']
    newsTable=News.objects.get(id=news_id)
    to=newsTable.user_id
    good_con=0
    time=timezone.now()
    re_of_news=Review_of_news(news_id=news_id,content=content,from_id=from_id,to=to,good_con=good_con,time=time)
    re_of_news.save()
    re_news_id=re_of_news.id
    newsTable.review_con=int(newsTable.review_con)+1
    newsTable.save()
    info=Info.objects.get(user_id=from_id)
    strr=str(re_news_id)+','+str(news_id)+','+str(content)+','+str(from_id)+','+str(info.user_name)+','+str(info.img)+','+str(good_con)+','+str(re_of_news.review_con)+','+str(to)
            #0					#1  			#2 				#3 							#4 				#5						#6			#7							#8
    warning_mesTable=Warning_mes(from_id=int(from_id),to=int(to),aim_id=int(news_id),status=3,review_id=int(re_news_id))
    warning_mesTable.save()
    #返回到前端js操作返回的数据
    return HttpResponse(strr)

#新鲜事回复的回复
def cocomment(request):
    news_id=request.GET['news_id']
    content=request.GET['content']
    re_id=request.GET['re_id']
    to=request.GET['to']
    from_id=request.session['id']
    good_con=0
    time=timezone.now()
    re_of_news=Review_of_news(news_id=news_id,content=content,from_id=from_id,to=to,good_con=good_con,time=time)
    re_of_news.save()
    re_news_id=re_of_news.id
    newsTable=News.objects.get(id=news_id)
    newsTable.review_con=int(newsTable.review_con)+1
    newsTable.save()
    beihuifu_re=Review_of_news.objects.get(id=re_id)
    beihuifu_re.review_con=int(beihuifu_re.review_con)+1
    beihuifu_re.save()
    info=Info.objects.get(user_id=from_id)
    strr=str(re_news_id)+','+str(news_id)+','+str(content)+','+str(from_id)+','+str(info.user_name)+','+str(info.img)+','+str(good_con)+','+str(re_of_news.review_con)+','+str(to)
            #0					#1  			#2 				#3 							#4 				#5						#6			#7							#8
    warning_mesTable=Warning_mes(from_id=int(from_id),to=int(to),aim_id=news_id,status=5,review_id=int(re_news_id))
    warning_mesTable.save()
    #返回到前端js操作返回的数据
    return HttpResponse(strr)

#加载更多回复
def get_more_re(request):
    news_id=request.GET['news_id']
    re_of_news=Review_of_news.objects.filter(news_id=news_id).order_by('time')
    strr=''
    for r in re_of_news:
        info=Info.objects.get(user_id=r.from_id)
        strr+=str(r.id)+','+str(news_id)+','+str(r.content)+','+str(r.from_id)+','+str(info.user_name)+','+str(info.img)+','+str(r.good_con)+','+str(r.review_con)+','+str(r.to)+','+str(r.time)+'*'
                #0				#1 				#2 				#3 					#4 						#5					#6					#7 					#8 				#9
    return HttpResponse(strr)

#给回复点赞
def cogood(request):
    entire=Good_review_of_news.objects.filter(review_of_news_id=request.GET['reviewOfNews_id'])
    for i in entire:
        if request.session['id']==i.user_id:
            return HttpResponse('2')
    Good_review_of_news(review_of_news_id=request.GET['reviewOfNews_id'],user_id=request.session['id']).save()
    n=Review_of_news.objects.get(id=request.GET['reviewOfNews_id'])
    g=int(n.good_con)+int(1)
    n.good_con=g
    n_news_id=n.news_id
    to=n.from_id
    n.save()
    #设置一条提醒
    try:
        if_exit_good_table=Warning_mes.objects.filter(aim_id=int(n_news_id)).filter(to=int(to)).get(status=13)
    except:
        if_exit_good_table=0

    if if_exit_good_table==0:
        warning_mesTable=Warning_mes(from_id=int(request.session['id']),to=int(to),aim_id=int(n_news_id),status=13,review_id=int(request.GET['reviewOfNews_id']))
        warning_mesTable.save()

    return HttpResponse('1')

#发私信
def message(request):
    realto=News.objects.get(id=request.GET['to'])
    Message(from_id=request.session['id'],to=realto.user_id,content=request.GET['message'],status=1).save()
    return HttpResponse('1')

def mytopic(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    return render(request,'users/myTopic.html')

#发布者权限申请
def teacherapply(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    try:
        tj=time.time()
        if 'idpic' in request.FILES:
            u=request.FILES['idpic']
            #i=base64.decodestring(u[1])
            #suffix=request.POST['img'].name.split('.')[-1]
            dirs="templates/picture/ID/"+str(tj)
            files=open(dirs, "w")
            files.write(u.read())
            files.close()
        #每一项都是必须的
        Teacher(user_id=request.session['id'],real_name=request.POST['realname'],sex=request.POST['sex'],alipay=request.POST['alipay'],identity=request.POST['id'],tel=request.POST['phone'],identity_img=str(tj)).save()

        return render(request,'users/success.html')
    except:
        info=Info.objects.get(user_id=request.session['id'])
        waningMes=warn(request.session['id'])[0]
        havent=warn(request.session['id'])[1]
        mess=warn(request.session['id'])[2]
        return render(request,'users/teacherApply.html',{'info':info,'waningMes':waningMes,'havent':havent,'message':mess})

#删除
def dlt(request):
    try:
        #删除已经购买的课程
        if int(request.GET['method'])==1:
            Purchase.objects.filter(user_id=request.session['id']).get(purchase_id=request.GET['id']).delete()
        #删除收藏的课程
        elif int(request.GET['method'])==2:
            Follow_course.objects.filter(user_id=request.session['id']).get(follow_course_id=request.GET['id']).delete()
        #删除悬赏的课程
        elif int(request.GET['method'])==3:
            Reward_course.objects.filter(user_id=request.session['id']).get(id=request.GET['id']).delete()
        return HttpResponse(1)
    except:
        return HttpResponse(2)

#课程延期
def expired(request):
    try:
        course=Course.objects.get(id=request.GET['course'])
        deadtime=str(course.deadline).split('.')
        deadline=deadtime[0]
        #延期30天
        timeArray=time.strptime(deadline,"%Y-%m-%d %H:%M:%S")
        timeStamp=int(time.mktime(timeArray))
        x=time.localtime(timeStamp+2592000)
        course.deadline=time.strftime('%Y-%m-%d %H:%M:%S',x)
        course.save()
        return HttpResponse(1)
    except:
        return HttpResponse(2)

#更改课程价格
def alter(request):
    try:
        course=Course.objects.get(id=request.GET['course'])
        course.price=request.GET['new']
        course.save()
        return HttpResponse(1)
    except:
        return HttpResponse(2)


    """
    提醒
    提醒分为13种：1.悬赏被揭棒 2.课程被购买 3.新鲜事被回复 4.话题被回复 5.新鲜事的回复被回复
    6.话题的回复被回复 7.悬赏所需的课程做完了 8.揭棒者被选定 9.新鲜事点赞 10.课程被评论
    11.悬赏被评论 12.话题的回复被点了赞 13.新鲜事的回复被点赞

    其中需要注意：当status为 3 or 5 or 9 or 13 时，需要记录回复的新鲜事的id，再根据id找到新鲜事页数&定位这条新鲜事
            当status为 4 or 10 or 11 时，记录了评论的id；其中，当statsu为 10 or 11时，定位到评论的位置
    """
def warning(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    info=Info.objects.get(user_id=request.session['id'])
    waningTable=Warning_mes.objects.filter(to=request.session['id']).order_by('-time')
    warning=[]
    for w in waningTable:
        each=[]
        each.append(w.from_id)		#0
        w_from_name=Info.objects.get(user_id=w.from_id).user_name
        each.append(w_from_name)	#1
        each.append(w.aim_id)	#2
        if w.status==1 or w.status==7 or w.status==8 or w.status==11:
            aim_name=Reward.objects.get(id=w.aim_id).name
        elif w.status==2 or w.status==10:
            aim_name=Course.objects.get(id=w.aim_id).name
        elif w.status==3 or w.status==5 or w.status==9 or w.status==13:
            aim_name=News.objects.get(id=w.aim_id).content
        elif w.status==4 or w.status==6 or w.status==12:
            aim_name=Topic.objects.get(id=w.aim_id).name
        each.append(aim_name[0:40]+'...')				#3
        each.append(w.status)				#4
        each.append(w.if_read)				#5
        each.append(w.time)				#6
        each.append(w.review_id)				#7
        each.append(w.id)				#8
        warning.append(each)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/warning.html',{'warning':warning,'info':info,'waningMes':waningMes,'havent':havent,'message':mess})

#显示所有私信
def mes(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    info=Info.objects.get(user_id=request.session['id'])
    messageTable=Message.objects.filter(to=request.session['id']).order_by('-time')
    message=[]
    for m in messageTable:
        each=[]
        each.append(m.from_id)		#0
        from_name=Info.objects.get(user_id=m.from_id).user_name
        each.append(from_name)		#1
        each.append(m.content)		#2
        each.append(m.time)		#3
        each.append(m.status)		#4
        each.append(m.id)		#5
        message.append(each)

    limit = 15
    paginator = Paginator(message, limit)
    page = request.GET.get('page')
    try:
        message = paginator.page(page)
    except PageNotAnInteger:
        message = paginator.page(1)
    except EmptyPage:
        message = paginator.page(paginator.num_pages)
    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/message.html',{'info':info,'messages':message,'waningMes':waningMes,'havent':havent,'message':mess})

#删除一条私信
def delames(request):
    mes_id=request.GET['mes_id']
    the_mes=Message.objects.get(id=mes_id)
    the_mes.delete()

    return HttpResponse('1')

#删除一条提醒
def delawarning(request):
    warning_id=request.GET['warning_id']
    the_warning=Warning_mes.objects.get(id=warning_id)
    the_warning.delete()

    return HttpResponse('1')

#显示与一个人的所有对话
def mestalk(request,from_id):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    info=Info.objects.get(user_id=request.session['id'])

    to=request.session['id']
    #messageTable=Message.objects.filter(from_id=from_id).filter(to=to).order_by('-time')
    messageTable=Message.objects.filter( Q(Q(from_id=from_id)&Q(to=to)) | Q(Q(from_id=to)&Q(to=from_id)) ).order_by('-time')
    message=[]
    for m in messageTable:
        each=[]
        each.append(m.from_id)		#0
        the_person=Info.objects.get(user_id=m.from_id)
        from_name=the_person.user_name
        from_img=the_person.img
        from_domain=the_person.domain
        each.append(from_name)		#1
        each.append(from_img)		#2
        each.append(from_domain)		#3
        each.append(m.content)		#4
        each.append(m.time)		#5
        message.append(each)


    limit = 15
    paginator = Paginator(message, limit)
    page = request.GET.get('page')
    try:
        message = paginator.page(page)
    except PageNotAnInteger:
        message = paginator.page(1)
    except EmptyPage:
        message = paginator.page(paginator.num_pages)

    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    return render(request,'users/mes_talk.html',{'talkto':from_id,'info':info,'messages':message,'waningMes':waningMes,'havent':havent,'message':mess})

#点击阅读一条私信时，以对话形式显示两人之间所有的私信。此方法用于将两人之间的私信全部设为已读
def mes_read(request):
    from_id=int(request.GET['from_id'])
    mesTable=Message.objects.filter(from_id=from_id).filter(to=request.session['id'])
    for m in mesTable:
        m.status=2
        m.save()

    return HttpResponse(1)

#选定揭棒者
def select(request):
    reward=Reward.objects.get(id=request.GET['reward'])
    reward.to=request.GET['user']
    reward.status=2
    reward.save()
    uncover=Uncover.objects.filter(reward_id=request.GET['reward']).get(to=request.GET['user'])
    uncover.status=1
    uncover.save()

    warning_mesTable=Warning_mes(from_id=int(request.session['id']),to=int(request.GET['user']),aim_id=int(request.GET['reward']),status=8)
    warning_mesTable.save()

    return HttpResponse(1)

#删除悬赏
def det(request):
    try:
        Reward.objects.get(id=request.GET['reward']).delete()
        return HttpResponse(1)
    except:
        return HttpResponse(2)

#删除提示
def del_warning(request):
    to=request.session['id']
    Warning_mes.objects.filter(to=to).delete()
    return HttpResponse(1)

#无视提醒
def ignore_warning(request):
    to=request.session['id']
    warning=Warning_mes.objects.filter(to=to).filter(if_read=0)
    for w in warning:
        w.if_read=1
        w.save()
    return HttpResponse(1)

#删除私信
def del_message(request):
    to=request.session['id']
    Message.objects.filter(to=to).delete()
    return HttpResponse(1)

#无视私信
def ignore_message(request):
    to=request.session['id']
    message=Message.objects.filter(to=to).filter(status=1)
    for m in message:
        m.status=2
        m.save()
    return HttpResponse(1)

#登出
def logout(request):
    del request.session['id']
    #return HttpResponse(request.session)
    return HttpResponseRedirect(reverse('login:index'))

#协议,1:用户协议,2:小组协议,3:课程协议.
def agreement(request,method):

    info=Info.objects.get(user_id=request.session['id'])

    waningMes=warn(request.session['id'])[0]
    havent=warn(request.session['id'])[1]
    mess=warn(request.session['id'])[2]
    #1:用户协议
    if int(method) == 1 :
        return render(request,'courses/agreement_user.html',{'info':info,'havent':havent,'message':mess,'waningMes':waningMes})
    #2:小组协议
    elif int(method) == 2 :
        return render(request,'courses/agreement_group.html',{'info':info,'havent':havent,'message':mess,'waningMes':waningMes})
    #3:课程协议
    elif int(method) == 3 :
        return render(request,'courses/agreement_course.html',{'info':info,'havent':havent,'message':mess,'waningMes':waningMes})
    else:
        return HttpResponse('没有此协议!')

#信息反馈
def feedback(request):
    if not 'id' in request.session:
        return HttpResponseRedirect(reverse('login:index'))
    return render(request,'users/feedback.html')

#反馈的数据库操作
@csrf_exempt
def addFeedback(request):
    Feedback(user=request.session['id'],content=request.POST['content']).save()
    return HttpResponse(1)